//
//  ChooseStorageViewController.m
//  FruitsAndHealthy
//
//  Created by appying_wxj on 14/11/14.
//  Copyright (c) 2014年 appying_wxj. All rights reserved.
//

#import "ChooseStorageViewController.h"
#import "ChooseDetailViewController.h"
#import "UIImageView+ASIRequest.h"
@interface ChooseStorageViewController ()

@end

@implementation ChooseStorageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.titleLab.text = @"选购和存储";
    [self initChooseAndStorage];

    if ([AllRequest checkNet]) {
        [MBProgressHUD showHUDAddedTo:self.storageTableView animated:YES];
        [self getChooseAndStorageDate];
        [self.storageTableView reloadData];
        [MBProgressHUD hideHUDForView:self.storageTableView animated:YES];
        

    }
           // Do any additional setup after loading the view.
}
// 初始化界面
-(void)initChooseAndStorage{

    // 导航条左边的按钮
    [self.leftButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _storageTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, kScreen_Height-64) style:UITableViewStylePlain];
    _storageTableView.backgroundColor = [UIColor whiteColor];
    _storageTableView.delegate = self;
    _storageTableView.dataSource = self;
    _storageTableView.rowHeight = 110;
    _storageTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _storageTableView.separatorStyle = NO;
    [self.view addSubview:_storageTableView];
    [self setExtraCellLineHidden:_storageTableView];
    
    // 2.集成刷新控件
    [self setupRefresh];

}
// 获取数据
-(void)getChooseAndStorageDate{
    _storageAllArray = [[NSMutableArray alloc] initWithCapacity:0];
    _storageTitleArray = [[NSMutableArray alloc] initWithCapacity:0];
    _storageContentsArray = [[NSMutableArray alloc] initWithCapacity:0];
    _storageImageArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    _chooseArray = [[NSMutableArray alloc] initWithCapacity:0];
    _storageArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    _storageBigImage = [[NSMutableArray alloc] initWithCapacity:0];
    
    AVQuery *fruits = [AVQuery queryWithClassName:@"chooseStorage"];
    [fruits findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {// 获取数据成功
            _storageAllArray = [NSMutableArray arrayWithArray:objects];
            for (int i = 0; i < _storageAllArray.count; i++) {
                AVObject *fruitsName = [_storageAllArray objectAtIndex:i];
                [_storageTitleArray addObject:[fruitsName objectForKey:@"headline"]];
                [_storageContentsArray addObject:[fruitsName objectForKey:@"contents"]];
                [_storageImageArray addObject:[fruitsName objectForKey:@"chooseImage"]];
                [_chooseArray addObject:[fruitsName objectForKey:@"choose"]];
                [_storageArray addObject:[fruitsName objectForKey:@"storage"]];
                [_storageBigImage addObject:[fruitsName objectForKey:@"bigImage"]];
            }
            [_storageTableView reloadData];
        } else {
            // 获取数据失败
        }
    }];
    
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh {
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_storageTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // 自动刷新(一进入程序就下拉刷新)
    //[self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_storageTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _storageTableView.headerPullToRefreshText = @"下拉可以刷新了";
    _storageTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    _storageTableView.headerRefreshingText = @"正在刷新中";
    
    _storageTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    _storageTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    _storageTableView.footerRefreshingText = @"正在加载中";
}
#pragma mark 开始进入刷新状态
// 下拉刷新
- (void)headerRereshing {
    //    // 1.添加数据
    //    for (int i = 0; i<5; i++) {
    ////        [self.fakeData insertObject:[self string] atIndex:0];
    //        [self getAllDate];
    //    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_storageTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_storageTableView headerEndRefreshing];
    });
}
// 上提加载
- (void)footerRereshing {
    // 1.添加假数据
    //    for (int i = 0; i<5; i++) {
    ////        [_fruitsTableView addObject:[self string]];
    //        [self getAllDate];
    //    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_storageTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_storageTableView footerEndRefreshing];
    });
}
//隐藏表格多余分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView {
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}

#pragma mark------UITableViewDataSource  delegate----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _storageAllArray.count / 3 + 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    else{
        while ([cell.contentView.subviews lastObject]!=nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    // 分割的线
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(10, 109.5, kScreen_Width-20, 0.5)];
    line.backgroundColor = [UIColor colorWithRed:0.91 green:0.94 blue:0.79 alpha:1];
    [cell.contentView addSubview:line];
    
    if (indexPath.row<_storageAllArray.count) {
        
        int V = _storageAllArray.count / 3 + 1;
        
        for (int i=0; (indexPath.row < V - 1) ? i < 3 : i < _storageAllArray.count % 3; i++)
        {
           

            _imageFile = [_storageBigImage objectAtIndex:(3 * indexPath.row + i)];
            NSString *imageStr = _imageFile.url;
            UIImageView *bigImage = [[UIImageView alloc] initWithFrame:CGRectMake(10+i%3*(95+10), 5, 95, 70)];
            bigImage.userInteractionEnabled = YES;
            [bigImage loadImageFromURL:imageStr showLoadingImg:@""];
            [bigImage setHidden:YES];
            [cell.contentView addSubview:bigImage];
            
            
            AVFile *applicantResume = [_storageImageArray objectAtIndex:(3 * indexPath.row + i)];
            _imagestring = applicantResume.url;
            UIImageView *userImage = [[UIImageView alloc] initWithFrame:CGRectMake(10+i%3*(95+10), 5, 95, 70)];
            userImage.userInteractionEnabled = YES;
            [userImage loadImageFromURL:_imagestring showLoadingImg:@""];
            [cell.contentView addSubview:userImage];
            
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [button setBackgroundColor:[UIColor clearColor]];
//            [button setTitle:[_storageImageArray objectAtIndex:(3 * indexPath.row + i)] forState:UIControlStateNormal];
            button.tag = indexPath.row*3+i+1000;
            button.frame = CGRectMake(0, 0, 95, 70);
            [button addTarget:self action:@selector(cellListButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [userImage addSubview:button];
            
            
            UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(10+i%3*(95+10), 75, 95, 30)];
            titleLab.text = [_storageTitleArray objectAtIndex:(3 * indexPath.row + i)];
            titleLab.textAlignment = NSTextAlignmentCenter;
            titleLab.font = [UIFont systemFontOfSize:14];
            titleLab.textColor = [UIColor colorWithRed:0.66 green:0.6 blue:0.12 alpha:1];
            [cell.contentView addSubview:titleLab];
            
            
        }
        
    }
    return cell;
    
}
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    dispatch_async(dispatch_get_main_queue(), ^
//                   {
//                       
//                       ChooseDetailViewController *chooseDetail = [[ChooseDetailViewController alloc] init];
//                       chooseDetail.chooseDetailContent = [_storageContentsArray objectAtIndex:indexPath.row];
//                       chooseDetail.chooseTitle = [_storageTitleArray objectAtIndex:indexPath.row];
//                       [self presentViewController:chooseDetail animated:YES completion:nil];
//                       
//                   });
//}

#pragma mark------ButtonClick-------
-(void)backButtonClick:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)cellListButtonClick:(UIButton *)sender{
    ChooseDetailViewController *chooseDetail = [[ChooseDetailViewController alloc] init];
    chooseDetail.chooseDetailContent = [_storageContentsArray objectAtIndex:sender.tag-1000];
    chooseDetail.chooseTitle = [_storageTitleArray objectAtIndex:sender.tag-1000];
    chooseDetail.chooseDetails = [_chooseArray objectAtIndex:sender.tag-1000];
    chooseDetail.storageDetails = [_storageArray objectAtIndex:sender.tag-1000];
    
    _imageFile = [_storageBigImage objectAtIndex:sender.tag-1000];
//    NSString *string1 = applicantResume1.url;
    
    chooseDetail.bigImageString = _imageFile;
   
//    NSLog(@"-----------%@------------",_imageFile);
    [self presentViewController:chooseDetail animated:YES completion:nil];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
